<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="cartInfo in cartInfoList"
          :key="cartInfo.id"
        >
          <li class="cart-list-con1">
            <!-- 点击可选框发送请求更新购物车数据 -->
            <input
              type="checkbox"
              name="chk_list"
              :checked="!!cartInfo.isChecked"
              @change="checkCartInfoState(cartInfo)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeSkuNum('decrement', cartInfo)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('change', cartInfo, $event)"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="changeSkuNum('increment', cartInfo)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuNum * cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              @click="showDialogByDelOneCartInfo(cartInfo.skuId)"
              href="javascript:;"
              class="sindelet"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input
          v-model="checkAll"
          :disabled="this.cartInfoList?.length === 0"
          class="chooseAll"
          type="checkbox"
        />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="delAllShopCartList">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span> {{ selectedCount }} </span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectedMoney }}</i>
        </div>
        <div class="sumbtn">
          <router-link to="/trade" class="sum-btn" href="javascript:;" >结算</router-link>
        </div>
      </div>
    </div>

    <!-- 弹出框 -->
    <Dialog :visible.sync="visible">
      <template v-slot:header>提示</template>
      <template
        ><p>
          您真的要删除<span style="color: red">{{
            isDelOne ? "此条" : "这些选中的"
          }}</span
          >数据吗?
        </p></template
      >
      <template #footer>
        <div class="btn-footer">
          <button class="btn btn-cancle" @click="visible = false">取消</button>
          <button @click="delShopCartInfo" class="btn btn-primary">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqGetShopCartListData,
  reqPostAddOrUpdateSkuInfoToShopCart,
  reqGetChangeCartListData,
  reqPostChangeAllShopCartInfoState,
  reqDelOneShopCartInfo,
  reqDelAllShopCartInfo,
} from "@/api";
import Dialog from "@/components/Dialog";
import { skuNumReg } from "@/utils/reg";
export default {
  name: "ShopCart",
  components: { Dialog },
  data() {
    return {
      cartInfoList: [],
      skuIdList: [],
      skuId: "",
      visible: false, //默认值
      isDelOne: false,
      leftCartInfoList: [], // 剩余未删除的商品
      num:0,
      timeId:null
    };
  },
  async mounted() {
    const result = await reqGetShopCartListData();
    // console.log('shopcart',result);
    if (result.code === 200) {
      // console.log(result);
      this.cartInfoList = result.data[0]?.cartInfoList;
    } else {
      console.log(result.message);
    }
  },
  methods: {
    // 更改商品的选中状态
    async checkCartInfoState(cartInfo) {
      let isChecked = 1 - cartInfo.isChecked;
      const result = await reqGetChangeCartListData(cartInfo.skuId, isChecked);
      if (result.code === 200) {
        alert("状态更新成功...");
      } else {
        console.log(result.message);
      }
      // 更新服务器数据后，再重新更新页面
      cartInfo.isChecked = isChecked;
    },
    //2. 删除一个商品时的弹出框
    showDialogByDelOneCartInfo(skuId) {
      this.skuId = skuId;
      this.visible = true;
      this.isDelOne = true;
    },
    // 批量删除商品
    delAllShopCartList() {
      // 清空数组，弹出对话框，用foreach遍历收集被选中的商品id，和剩余的商品id在批量删除后遍历剩余的商品区分批量删除

      this.skuIdList = [];
      this.leftCartInfoList = [];
      this.visible = true;
      this.cartInfoList.forEach((cartInfo) => {
        if (cartInfo.isChecked) {
          this.skuIdList.push(cartInfo.skuId);
        } else {
          this.leftCartInfoList.push(cartInfo);
        }
      });
      this.isDelOne = false;
    },

    //  删除购物车中的一件商品：点击删除按钮弹出对话框，且确定是删除一个商品(isDel);在确定删除按钮中判断是删除一条还是批量删除(isDel是true还是false)
    // 批量删除按钮注册事件写逻辑，根据skuIdList，发送请求
    async delShopCartInfo() {
      if (this.isDelOne) {
        const result = await reqDelOneShopCartInfo(this.skuId);

        if (result.code === 200) {
          this.visible = false; //隐藏对话框
          this.cartInfoList = this.cartInfoList?.filter(
            (cartInfo) => cartInfo.skuId !== this.skuId
          );
        } else {
          console.log(result.message);
        }
        return;
      }

      // 否则就是批量删除
      const result = await reqDelAllShopCartInfo(this.skuIdList);
      console.log(result);
      if (result.code === 200) {
        this.visible = false; //隐藏对话框
        this.cartInfoList = this.leftCartInfoList;
      } else {
        console.log(result.message);
      }
    },

    async changeSkuNum(type, cartInfo, $event) {
      // let num = 0;
      let { skuId, skuNum } = cartInfo;
      switch (type) {
        case "increment":
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++;
            // num++;
            this.num++;
          }

          break;

        case "decrement":
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum--;
            // num--;
            this.num--;
          }
          break;

        case "change":
          let newSkuNum = $event.target.value;
          if (newSkuNum === "") newSkuNum = 1;
          // console.log(newSkuNum);
          if (skuNumReg.test(newSkuNum)) {
            this.num = newSkuNum - cartInfo.skuNum;
            cartInfo.skuNum = newSkuNum;

            if (newSkuNum > 200) {
              this.num = cartInfo.skuNum - 200;
              cartInfo.skuNum = 200;
            }
          } else {
            e.target.value = cartInfo.skuNum;
          }

          break;
      }
      if (this.num == 0) return;

      // 添加防抖，快速点击多次后发送的值是累加的
      if(this.timeId) clearTimeout(this.timeId)
      this.timeId = setTimeout(async() => {
        const result = await reqPostAddOrUpdateSkuInfoToShopCart(skuId, this.num);
        if (result.code === 200) {
        // 后期可以加入element-ui框架中的提示功能
        this.num = 0
        this.$message({
          type:'success',
          message:'更改数据成功'
        })

        } else {
        console.log(result.message);

      }
      },1000)
    },
  },
  computed: {
    checkAll: {
      get() {
        return (
          this.cartInfoList?.every((cartInfo) => cartInfo.isChecked === 1) &&
          this.cartInfoList?.length
        );
      },
      async set(val) {
        console.log("val", val);

        let isChecked = val ? 1 : 0;

        const skuIdList = []; // 定义一个变量数组 来存储所有的要更新状态的商品skuId

        this.cartInfoList?.forEach((cartInfo) => {
          cartInfo.isChecked = isChecked;

          skuIdList.push(cartInfo.skuId);
          //将商品的选中状态批量的更新回服务器
          // this.checkCartInfoState({skuId:cartInfo.skuId,isChecked:1-isChecked})
        });
        const result = await reqPostChangeAllShopCartInfoState(
          isChecked,
          skuIdList
        );
        if (result.code === 200) {
          alert("批量更新商品状态成功");
        } else {
          console.log("更新失败", result.message);
        }
      },
    },
    selectedCount() {
      return this.cartInfoList?.reduce(
        (prev, current) => prev + current.isChecked,
        0
      );
    },
    selectedMoney() {
      return this.cartInfoList?.reduce(
        (prev, current) =>
          prev + current.isChecked * current.skuPrice * current.skuNum,
        0
      );
    },
  },
  watch: {
    visible: {
      immediate: true,
      handler() {
        if (this.visible) {
          document.documentElement.style.overflow = "hidden";
        } else {
          document.documentElement.style.overflow = "auto";
        }
      },
    },
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
  .btn-footer {
    position: absolute;
    right: 40px;
    bottom: 20px;
    .btn {
      width: 62px;
      height: 32px;
      font-size: 14px;
      margin-left: 16px;
      border-width: 1px;
      border-radius: 10%;
      cursor: pointer;
    }
    .btn-primary {
      background-color: rgb(102, 177, 255);
      color: #fff;
      &:hover {
        background-color: #66b1ff;
      }
    }

    .btn-cancle {
      border: 1px solid #ccc;
      &:hover {
        background-color: #ecf5ff;
        color: #66b1ff;
      }
    }
  }
}
</style>